package com.lemon.smartsafetynew.ui.fragment.base;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.event.base.AppEvent;
import com.lemon.smartsafetynew.ui.activity.base.LemonPermissionListener;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesHelper;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.permission.AfterPermissionGranted;
import cn.finalteam.galleryfinal.permission.EasyPermissions;

/**
 * Created by SilenceDut on 2015/11/28.
 */
public abstract class BaseFragment extends Fragment implements EasyPermissions.PermissionCallbacks {

    public static final  String TAG              = "BaseFragment";
    private static final int    PERMISSIONS_CODE = 1217;
    protected View rootView;

    protected SharedPreferencesHelper mSharedPreferencesHelper;

    private LemonPermissionListener mPermissionListener;


    protected HUDUtil mHUDUtil;

    /**
     * 在初始化视图前一些参数的获取
     */
    protected abstract void getBaseArguments();


    private Activity mContext;

    public Activity getmContext() {
        return mContext;
    }

    /**
     * 设置视图的布局文件
     *
     * @return
     */
    protected abstract int getContentViewId();

    /**
     * 一些初始化UI有关的都在这里
     */
    protected abstract void initViews();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppService.getInstance().getBus().register(this);
        mContext = getActivity();
        if (mHUDUtil == null) {
            mHUDUtil=new HUDUtil();
            mHUDUtil = mHUDUtil.init(getActivity());
            //mHUDUtil = HUDUtil.init(mContext);
        }
        mSharedPreferencesHelper = new SharedPreferencesHelper(IApplication.context());
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getBaseArguments();
        rootView = inflater.inflate(getContentViewId(), container, false);
        mHUDUtil=new HUDUtil();
        mHUDUtil = mHUDUtil.init(getActivity());
        //mHUDUtil = HUDUtil.init(mContext);
        ButterKnife.bind(this, rootView);
        initViews();
        return rootView;
    }

    public MaterialDialog.Builder getConfirmDialog(Context context, String content, MaterialDialog.SingleButtonCallback callback) {
        return new MaterialDialog.Builder(context).title(getString(R.string.tip_str_title))
                                                  .content(content)
                                                  .positiveText(R.string.sure_str)
                                                  .negativeText(R.string.cancel_str)
                                                  .onAny(callback);
    }

    public MaterialDialog.Builder getConfirmDialog(String content, MaterialDialog.SingleButtonCallback callback) {
        return new MaterialDialog.Builder(getActivity()).title(getString(R.string.tip_str_title))
                                                        .content(content)
                                                        .positiveText(R.string.sure_str)
                                                        .negativeText(R.string.cancel_str)
                                                        .onAny(callback);
    }

    /**
     * 是否是Android M （23版本号）
     *
     * @return
     */
    public boolean isAndroidM() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return true;
        }
        return false;
    }

    public void checkPermission(String message, LemonPermissionListener listener, String... permissions) {
        checkPermission(message, getString(R.string.permission_denied_tip), listener, permissions);
    }

    @AfterPermissionGranted(PERMISSIONS_CODE)
    public void checkPermission(String message, String deniedMessage, LemonPermissionListener listener, String... permissions) {
        this.mPermissionListener = listener;
        if (EasyPermissions.hasPermissions(getActivity(), permissions)) {
            listener.onPermissionGranted(PERMISSIONS_CODE);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, message, PERMISSIONS_CODE, permissions);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        this.mPermissionListener.onPermissionGranted(requestCode);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        this.mPermissionListener.onPermissionDenied(requestCode, (ArrayList<String>) list);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mHUDUtil != null) {
            mHUDUtil = null;
        }
        AppService.getInstance().getBus().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        GalleryFinal.cleanCoreConfig();
        ButterKnife.unbind(this);
    }

    /**
     * Post Event Bus Event
     *
     * @param event
     */
    public void sendEvent(AppEvent event) {
        AppService.getBus().post(event);
    }


    /**
     * 获得一个顶部控件
     */
    public View getHeaderView(int message) {
        return getHeaderView(getString(message));
    }

    /**
     * 获得一个顶部控件
     */
    public View getHeaderView(String message) {
        return getHeaderView(message, R.color.colorTextPrimary);
    }


    /**
     * 获得一个顶部控件
     */
    public View getHeaderView(String message, int colorRes) {
        View     header     = LayoutInflater.from(getActivity())
                                            .inflate(R.layout.view_login_user_tip_head, (ViewGroup) getActivity().findViewById(android.R.id.content), false);
        TextView headerView = (TextView) header;
        headerView.setTextColor(getResources().getColor(colorRes));
        headerView.setText(message);
        return headerView;
    }

    @Subscribe
    public void onEventMainThread(AppEvent event) {
    }


    public void initGalleryFinalImageLoader() {
        ThemeConfig mThemeConfig = new ThemeConfig.Builder().setTitleBarBgColor(getResources().getColor(R.color.colorPrimary))
                                                            .setTitleBarTextColor(getResources().getColor(R.color.colorWhite))
                                                            .setTitleBarIconColor(getResources().getColor(R.color.colorWhite))
                                                            .setFabNornalColor(getResources().getColor(R.color.colorPrimary))
                                                            .setCheckSelectedColor(getResources().getColor(R.color.colorPrimary))//选择框选中颜色
                                                            .setFabPressedColor(getResources().getColor(R.color.colorPrimaryDark))
                                                            .build();
        FunctionConfig.Builder                mFunctionConfigBuilder = new FunctionConfig.Builder();
        cn.finalteam.galleryfinal.ImageLoader imageLoader            = new GlideImageLoader();

        CoreConfig.Builder mCoreConfigBuilder = new CoreConfig.Builder(getContext(), imageLoader, mThemeConfig).setFunctionConfig(mFunctionConfigBuilder
                                                                                                                                          .build());
        GalleryFinal.init(mCoreConfigBuilder.build());
    }


    /**
     * 查找View
     *
     * @param id   控件的id
     * @param <VT> View类型
     * @return
     */
    public <VT extends View> VT getViewById(@IdRes int id) {
        return (VT) rootView.findViewById(id);
    }
}
